import { IBuildTaskOption, BuildHook, IBuildResult } from '../@types';
import {copySync, existsSync, outputFile, outputFileSync, readFileSync} from "fs-extra";
import * as path from "path";
import {generateRuntimeCheckCode} from "../runtime-check/src/generateRuntimeCheckCode";
import {handleFileContent} from "../runtime-check/src/processCodeFile";
import {AssetInfo} from "../@types/packages/asset-db/@types/public";
import UglifyJS from "../uglify-js/tools/node";
import {ob} from "../runtime-check/src/ob";


interface IOptions {
    obCode: boolean
    runtimeCheck: boolean
    targetEnvVersionMap: {
        develop: boolean,
        trial: boolean,
        release: boolean,
    }
    // remoteAddress: string;
    // enterCocos: string;
    // selectTest: string;
    // objectTest: {
    //     number: number;
    //     string: string;
    //     boolean: boolean
    // },
    // arrayTest: [number, string, boolean];
}

const PACKAGE_NAME = 'build-plugin-runtime-check';

interface ITaskOptions extends IBuildTaskOption {
    packages: {
        'build-plugin-runtime-check': IOptions;
        'wechatgame': {
            "orientation": string,
            "appid": string
            "buildOpenDataContextTemplate": string,
            "separateEngine": boolean,
            "highPerformanceMode": boolean,
            "enabelWebGL2": string,
            "wasm": string,
            "__version__": string
        }
    };
}

function log(...arg: any[]) {
    return console.log(`[${PACKAGE_NAME}] `, ...arg);
}

let allAssets: AssetInfo[] = [];

export const throwError: BuildHook.throwError = true;

export const load: BuildHook.load = async function() {
    console.log(`[${PACKAGE_NAME}] Load cocos plugin example in builder.`);
    allAssets = await Editor.Message.request('asset-db', 'query-assets');
};

export const onBeforeBuild: BuildHook.onBeforeBuild = async function(options: ITaskOptions, result: IBuildResult) {
    console.log(UglifyJS)

    log(`${PACKAGE_NAME}.webTestOption`, 'onBeforeBuild', JSON.stringify(options));
    if (options.platform !== "wechatgame") {
        return
    }

    const runtimeCheck = options.packages["build-plugin-runtime-check"].runtimeCheck;
    const obCode = options.packages["build-plugin-runtime-check"].obCode;
    const targetEnvVersionMap = options.packages["build-plugin-runtime-check"].targetEnvVersionMap;

    const appid = options.packages.wechatgame.appid;
    let typescriptAssets: AssetInfo[] = allAssets.filter((a) => a.importer == "typescript" && a.readonly == false)

    for (let typescriptAsset of typescriptAssets) {
        let content = readFileSync(typescriptAsset.file, {
            encoding: "utf-8"
        })
        let code = "";
        if (runtimeCheck) {
            if (obCode) {
                code = generateRuntimeCheckCode(appid, targetEnvVersionMap).code
            }
            else {
                code = generateRuntimeCheckCode(appid, targetEnvVersionMap).minify
            }
        }
        const newContent = handleFileContent(content, code);
        if (newContent != content) {
            console.log("write new content to " + typescriptAsset.file)
            outputFileSync(typescriptAsset.file, newContent);
        }
    }

};

export const onBeforeCompressSettings: BuildHook.onBeforeCompressSettings = async function(options: ITaskOptions, result: IBuildResult) {
    const pkgOptions = options.packages[PACKAGE_NAME];
    // if (pkgOptions.webTestOption) {
    //     console.debug('webTestOption', true);
    // }
    // Todo some thing
    // console.debug('get settings test', result.settings);
};

export const onAfterCompressSettings: BuildHook.onAfterCompressSettings = async function(options: ITaskOptions, result: IBuildResult) {
    // Todo some thing
    // console.log('webTestOption', 'onAfterCompressSettings');
};

export const onAfterBuild: BuildHook.onAfterBuild = async function(options: ITaskOptions, result: IBuildResult) {
    console.log(options)
    console.log(result)
    console.log(result.dest)

    const destDirName = path.basename(result.dest)
    const templatePath = path.join(Editor.Project.path, "build-templates", destDirName)

    console.log(destDirName)
    console.log(templatePath)

    if (existsSync(templatePath)) {
        copySync(templatePath, result.dest);
    }

    const obCode = options.packages["build-plugin-runtime-check"].obCode;
    if (obCode) {
        ob(result.dest);
    }

    // change the uuid to test
    // const uuidTestMap = {
    //     image: '57520716-48c8-4a19-8acf-41c9f8777fb0',
    // };
    // for (const name of Object.keys(uuidTestMap)) {
    //     const uuid = uuidTestMap[name];
    //     console.debug(`containsAsset of ${name}`, result.containsAsset(uuid));
    //     console.debug(`getAssetPathInfo of ${name}`, result.getAssetPathInfo(uuid));
    //     console.debug(`getRawAssetPaths of ${name}`, result.getRawAssetPaths(uuid));
    //     console.debug(`getJsonPathInfo of ${name}`, result.getJsonPathInfo(uuid));
    // }
    // test onError hook
    // throw new Error('Test onError');
};

export const unload: BuildHook.unload = async function() {
    console.log(`[${PACKAGE_NAME}] Unload cocos plugin example in builder.`);
};

export const onError: BuildHook.onError = async function(options, result) {
    // Todo some thing
    console.warn(`${PACKAGE_NAME} run onError`);
};

export const onBeforeMake: BuildHook.onBeforeMake = async function(root, options) {
    console.log(`onBeforeMake: root: ${root}, options: ${options}`);
};

export const onAfterMake: BuildHook.onAfterMake = async function(root, options) {
    console.log(`onAfterMake: root: ${root}, options: ${options}`);
};
